import { defineStore } from 'pinia';
import { ref } from 'vue';
import pinia from '@/store';
import type { LoginParams } from '@/api/auth/model';
import { doLogout, getUserInfo, loginApi } from '@/api/auth';
import { removeToken, setToken } from '@/utils/auth';
import { PageEnum } from '@/enums/pageEnum';

export interface AppUserInfo {
  id: string;
  username: string;
  nickname: string;
  avatar: string;
  roles: string[];
  permissions: string[];
}

export const useUserStore = defineStore('app-user', () => {
  const token = ref<string | null>(null);
  const userInfo = ref<AppUserInfo | null>(null);

  async function login(params: LoginParams) {
    const { access_token } = await loginApi(params);
    token.value = access_token;
    setToken(access_token);
  }

  async function loadUserInfo(toIndexPage = true) {
    const { user, roles, permissions } = await getUserInfo();
    // 转换
    const appUserInfo: AppUserInfo = {
      id: user.userId,
      username: user.userName,
      nickname: user.nickName,
      avatar:
        user.avatar ||
        'https://plus.dapdap.top/minio-server/plus/2024/07/09/6dc37ade5147491bbb90ec8f40f46f04.jpg',
      roles,
      permissions,
    };
    userInfo.value = appUserInfo;
    if (toIndexPage) {
      uni.reLaunch({ url: PageEnum.Home });
    }
  }

  function resetState(toLoginPage = false) {
    token.value = null;
    userInfo.value = null;
    removeToken();
    if (toLoginPage) {
      uni.reLaunch({ url: PageEnum.Login });
    }
  }

  async function logout() {
    try {
      await doLogout();
    } catch (e) {
      console.warn(e);
    } finally {
      // resetState(true);
    }
  }

  return { token, userInfo, login, loadUserInfo, resetState, logout };
});

export function useUserStoreWithOut() {
  return useUserStore(pinia);
}
